<template>
  <div class="score-manage">
    <!-- 筛选条件 -->
    <el-form :inline="true" :model="scoreStore.queryForm" class="query-form">
      <el-form-item label="学号">
        <el-input
          v-model="scoreStore.queryForm.studentId"
          placeholder="请输入学号"
        />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          v-model="scoreStore.queryForm.name"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="课程">
        <el-select
          v-model="scoreStore.queryForm.course"
          placeholder="选择课程"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="c in scoreStore.courseList"
            :key="c"
            :label="c"
            :value="c"
            style="font-size: 15px"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="openDialog()">新增成绩</el-button>
      <el-button type="danger" @click="del">批量删除</el-button>
      <!-- <el-button type="success">批量导入</el-button>
      <el-button type="warning">导出成绩</el-button> -->
    </div>

    <!-- 成绩表格 -->
    <el-table
      :data="pagedData"
      border
      stripe
      style="width: 100%"
      @selection-change="selected"
      :row-style="{ height: '45px' }"
      max-height="60vh"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="studentId" label="学号" width="200" />
      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="course" label="课程" />
      <el-table-column prop="score" label="成绩" width="100" />
      <el-table-column prop="term" label="学期" width="150" />
      <el-table-column prop="createBy" label="录入人" width="120" />
      <el-table-column prop="createTime" label="录入时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <template v-if="scope.row.studentId">
            <el-button
              size="small"
              type="primary"
              plain
              @click="openDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              plain
              @click="remove(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <Pagination
      v-model:currentPage="currentPage"
      v-model:pageSize="pageSize"
      :total="scoreStore.tableData.length"
      @change="loadData"
    />

    <!-- 成绩录入 / 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="成绩录入" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="form.studentId" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="课程">
          <el-select v-model="form.course" placeholder="请选择课程">
            <el-option
              v-for="c in scoreStore.courseList"
              :key="c"
              :label="c"
              :value="c"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩">
          <el-input-number v-model="form.score" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="form.term" placeholder="请选择学期">
            <el-option
              v-for="t in scoreStore.termList"
              :key="t"
              :label="t"
              :value="t"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Pagination from '@/components/Pagination/index.vue' // 你封装的分页器
import useScoreStore from '@/store/modules/score'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const scoreStore = useScoreStore()

// 查询回调
const query = () => {
  scoreStore.queryData()
}

// 重置回调
const resetQuery = () => {
  scoreStore.reset()
}

// 分页器数据
const currentPage = ref(1)
const pageSize = ref(10)

// 补齐空行的计算属性
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const pageItems = scoreStore.tableData.slice(start, end)

  // 如果数据不够一页，用空对象补齐
  const emptyCount = pageSize.value - pageItems.length
  if (emptyCount > 0) {
    for (let i = 0; i < emptyCount; i++) {
      pageItems.push({
        id: NaN,
        studentId: '',
        name: '',
        course: '',
        score: '',
        term: '',
        createBy: '',
        createTime: '',
      })
    }
  }

  return pageItems
})

// 弹窗相关
const dialogVisible = ref(false)
const form = ref<any>({})
const openDialog = (row?: any) => {
  if (row && row.id) {
    // 编辑
    form.value = { ...row }
  } else {
    // 新增
    form.value = {
      id: NaN,
      studentId: '',
      name: '',
      course: '',
      score: 0,
      term: '',
      createBy: userStore.name,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    console.log(userStore)
  }
  dialogVisible.value = true
}
const save = () => {
  if (!form.value.studentId || !form.value.name || !form.value.course) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (isNaN(form.value.id)) {
    // 新增
    console.log(111)
    scoreStore.addScore({ ...form.value })
    ElMessage.success('新增成功')
  } else {
    // 编辑
    scoreStore.updateScore({ ...form.value })
    ElMessage.success('修改成功')
  }

  dialogVisible.value = false
}

// 删除总按钮（批量删除）
let idArr: any = []
const del = async () => {
  if (idArr.length === 0) {
    return ElMessage.warning('请选择要删除的数据')
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${idArr.length} 条记录吗？`,
      '是否确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
      },
    )
    // 用户点击确定
    scoreStore.removeBatch(idArr)
    ElMessage.success('删除成功')
    idArr = [] // 清空选中
  } catch (err) {
    // 用户点击取消，不做处理
  }
}

// 选中的复选框
const selected = (data: any) => {
  // console.log(data)
  idArr = [] // 重置
  data.forEach((value: any) => {
    if (value.id) {
      // 只记录真实数据，不包括空行
      idArr.push(value.id)
    }
  })
  // console.log("idArr:", idArr)
}

// 删除单行
const remove = async (id: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '是否确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
    })
    scoreStore.remove(id)
    ElMessage.success('删除成功')
  } catch (err) {
    // 取消时什么都不做
  }
}

const loadData = ({ page, pageSize }: { page: number; pageSize: number }) => {
  console.log('分页变化：', page, pageSize)
  // 如果是后端分页，可以在这里发请求
}
</script>

<style scoped lang="scss">
.score-manage {
  font-size: 15px;

  .query-form {
    margin-bottom: 20px;
  }

  .toolbar {
    margin-bottom: 15px;
  }

  .el-dialog {
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }
}
</style>
